package service

import (
	"errors"
	"golang.org/x/crypto/bcrypt"
	"golang.org/x/net/context"
	"internal/internal/domain"
	"internal/internal/repository"
	"internal/internal/repository/dao"
)

var ErrUserDuplicateEmail = repository.ErrUserDuplicateEmail

type UserService struct {
	repo *repository.UserRepository
}

func NewUserService(repo *repository.UserRepository) *UserService {
	return &UserService{
		repo: repo,
	}
}

// Signup 注册service层
func (svc *UserService) Signup(ctx context.Context, u domain.User) error {
	hash, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)
	if err != nil {
		return err
	}
	u.Password = string(hash)
	// 实现具体业务逻辑
	return svc.repo.Create(ctx, u)
}

func (svc *UserService) Login(ctx context.Context, user domain.User) (domain.User, error) {
	u, err := svc.repo.FindByName(ctx, user.Username)
	if errors.Is(err, repository.ErrUserNotFound) {
		return domain.User{}, dao.ErrInvalidUserOrPassword
	}
	if err != nil {
		return domain.User{}, err
	}

	err = bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(user.Password))
	if err != nil {
		return domain.User{}, dao.ErrInvalidUserOrPassword
	}
	return u, nil
}
